package lib

import (
	"context"
	"time"

	"gorm.io/gorm/logger"
)

type GormLogger struct {
	SlowThreshold time.Duration
}

func NewGormLogger() *GormLogger {
	return &GormLogger{
		SlowThreshold: 200 * time.Millisecond, // 一般超过200毫秒就算慢查所以不使用配置进行更改
	}
}

var _ logger.Interface = (*GormLogger)(nil)

func (l *GormLogger) LogMode(lev logger.LogLevel) logger.Interface {
	return &GormLogger{}
}
func (l *GormLogger) Info(ctx context.Context, msg string, data ...interface{}) {}
func (l *GormLogger) Warn(ctx context.Context, msg string, data ...interface{}) {}
func (l *GormLogger) Error(ctx context.Context, msg string, data ...interface{}) {
	// traceContext := TraceFromContext(ctx)
	// m := map[string]interface{}{
	// 	msg: msg,
	// }
	// Log.TagError(traceContext, DLTagMySql, m)
}
func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
	if !GetBoolConf("base.log.file_writer.on") {
		return
	}

	traceContext := TraceFromContext(ctx)

	// 获取运行时间
	elapsed := time.Since(begin)
	// 获取 SQL 语句和返回条数
	sql, rows := fc()
	// Gorm 错误时打印
	if err != nil {
		m := map[string]interface{}{
			"sql": sql,
			// "current_time": time.Now(),
			"msg": err.Error(),
		}
		Log.TagInfo(traceContext, DLTagMySqlFailed, m)
		return
	}

	m := map[string]interface{}{
		"sql": sql,
		// "current_time": time.Now(),
		"affected_row": rows,
		"proc_time":    elapsed,
	}
	// 慢查询日志
	if l.SlowThreshold != 0 && elapsed > l.SlowThreshold {
		Log.TagInfo(traceContext, DLTagMySqlSlow, m)
	} else {
		Log.TagInfo(traceContext, DLTagMySqlSuccess, m)
	}
}
